import { message } from 'ant-design-vue'
import type { AxiosError, AxiosResponse } from 'axios'
import { useUserStore } from '@/stores/user'

/**
 * 响应参数归一化处理
 * @param response 响应参数
 */
const normalizeResponse = (response: AxiosResponse) => {
  const { data } = response
  const code = data.rspCode ?? data.statusCode ?? null
  const msg = data.rspMsg ?? data.msg ?? ''
  return {
    ...data,
    code,
    msg,
  }
}

export const handleResponseSuccess = (response: AxiosResponse) => {
  try {
    if (['blob', 'arraybuffer'].includes(response.request.responseType)) {
      return response.data
    }
    const data = normalizeResponse(response)
    if (data.code) {
      message.error(data.msg)
      if ([401, 80001].includes(data.code)) {
        useUserStore().$reset()
        window.location.href = '/'
      }
    } else {
      return data
    }
  } catch (e) {
    console.error('后端返回参数不符合规范', e)
    return {
      data: null,
      code: null,
      msg: null,
    }
  }
}

export const handleResponseError = (error: AxiosError) => {
  const status = error.response?.status
  let msg: string = '请求错误'

  if (status) {
    switch (status) {
      case 400:
        msg = '请求参数错误'
        break
      case 401:
        useUserStore().$reset()
        window.location.href = '/'
        msg = '身份认证已过期'
        break
      case 403:
        msg = '拒绝访问'
        break
      case 404:
        msg = '资源不存在'
        break
      case 500:
        msg = '服务器内部错误'
        break
      case 503:
        msg = '服务不可用'
        break
      default:
        msg = `网络错误 (${status})`
    }
  } else if (error.code === 'ECONNABORTED') {
    msg = '请求超时'
  } else if (!window.navigator.onLine) {
    msg = '网络连接已断开'
  }

  message.error(msg)
}
